package com.leyou.search.service;


import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchService {


    @Autowired
    private ItemClient itemClient;





    public Goods buildGoods(SpuDTO spuDTO){

        //1。搜索字段 包含分类，品牌，标题等
        //1.1查询分类
        List<CategoryDTO> categoryDTOS = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        String categoryName = categoryDTOS.stream().map(CategoryDTO::getName).collect(Collectors.joining());
        //1.2查询品牌
        BrandDTO brandDTO = itemClient.queryById(spuDTO.getBrandId());
        //1.3拼接
        String all = spuDTO.getName() + categoryName + brandDTO.getName();
        //2.spu下的所有sku
        List<SkuDTO> skuDTOS = spuDTO.getSkus() == null ? itemClient.querySkuBySpuId(spuDTO.getId()) : spuDTO.getSkus();
        List<Map<String,Object>> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOS) {
            Map<String,Object> sku = new HashMap<>();
            sku.put("id",skuDTO.getId());
            sku.put("image", StringUtils.substringBefore(skuDTO.getImages(),","));
            sku.put("price",skuDTO.getPrice());
            sku.put("title",skuDTO.getTitle());
            skuList.add(sku);
        }
        //3。价格，spu下的所有sku价格
        Set<Long> price = skuDTOS.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());
        //4.规格参数，包含key和value
        Map<String,Object> specs = new HashMap<>();
        //4.1规格参数的key，当前商品所属分类的规格参数，必须是search为true
        List<SpecParamDTO> specParams = itemClient.querySpecParams(null, spuDTO.getCid3(), true);
        //4.2规格参数的值
        SpuDetailDTO detail = spuDTO.getSpuDetail() == null ? itemClient.querySpuDetailById(spuDTO.getId()) : spuDTO.getSpuDetail();
        //4.2.1 通用规格参数的值
        Map<Long, Object> genericSpec = JsonUtils.toMap(detail.getGenericSpec(), Long.class, Object.class);
        //4.2.2 特有规格参数的值
        Map<Long,List<Object>> specialSpec = JsonUtils.nativeRead(detail.getSpecialSpec(), new TypeReference<Map<Long, List<Object>>>() {
        });
        //4.3 封装数据
        for (SpecParamDTO param : specParams) {
            // 规格参数Name作为key
            String key = param.getName();
            //值，需要去genericSpec或specialSpec中去取
            Object value = null;
            //判断是否是通用规格参数
            if (param.getGeneric()){
                //通用
                value = genericSpec.get(param.getId());
            }else {
                //特有
                value = specialSpec.get(param.getId());
            }
            // 判断是否是数值类型，如果是，则需要处理数据分段
            if (param.getNumeric()){
                value = chooseSegment(value,param);
            }
            specs.put(key,value);
        }
        //5.创建goods
        Goods goods = new Goods();
        goods.setBrandId(spuDTO.getBrandId());
        goods.setCategoryId(spuDTO.getCid3());
        goods.setId(spuDTO.getId());
        goods.setCreateTime(spuDTO.getCreateTime().getTime());
        goods.setSubTitle(spuDTO.getSubTitle());
        goods.setAll(all); // 搜索字段 包含分类，品牌，标题等
        goods.setPrice(price); // 价格，spu下的所有sku价格
        goods.setSkus(JsonUtils.toString(skuList)); // spu下的所有sku
        goods.setSpecs(specs); // 规格参数，包含key和value
        return goods;

    }






    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private ElasticsearchTemplate esTemplate;





    public PageResult<GoodsDTO> search(SearchRequest searchRequest) {
        //0.健壮性判断
        String key = searchRequest.getKey();
        if (StringUtils.isBlank(key)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //1.创建原生搜索构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.组织条件
        //2.0 source过滤，控制字段数量
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id","subTitle","skus"},null));
        //2.1搜索条件
        QueryBuilder basicQueryBuilder = builderBasicQueryBuilder(searchRequest);
        queryBuilder.withQuery(basicQueryBuilder);
        //2.2分页条件
        Integer page = searchRequest.getPage() - 1;
        Integer size = searchRequest.getSize();
        queryBuilder.withPageable(PageRequest.of(page,size));
        //3.搜索结果
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);
        //4.解析结果
        //4.1解析分页数据
        long total = result.getTotalElements();//总条数
        int totalPage = result.getTotalPages();//总页数
        List<Goods> list = result.getContent();//当前页数据
        //4.2转换DTO
        List<GoodsDTO> dtoList = BeanHelper.copyWithCollection(list, GoodsDTO.class);
        //5.封装并返回
        return new PageResult<>(total,totalPage,dtoList);
    }





    private QueryBuilder builderBasicQueryBuilder(SearchRequest request) {
        //1.创建布尔查询，用来封装所有条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        //2.查询条件
        queryBuilder.must(QueryBuilders.matchQuery("all",request.getKey()).operator(Operator.AND));
        //3.过滤条件
        Map<String, String> filters = request.getFilter();
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                //获取过滤条件的key
                String key = entry.getKey();

                if ("分类".equals(key)) {
                    key = "categoryId";
                } else if ("品牌".equals(key)) {
                    key = "brandId";
                } else {
                    key = "specs." + key;
                }
                //value
                String value = entry.getValue();
                //添加过滤条件
                queryBuilder.filter(QueryBuilders.termQuery(key, value));

            }

        return queryBuilder;
    }





    public Map<String, List<?>> queryFilterList(SearchRequest request) {
        Map<String,List<?>> filterList = new LinkedHashMap<>();
        //1.创建原生搜索构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.添加过滤条件
        //2.1 搜索条件
        QueryBuilder basicQuery = builderBasicQueryBuilder(request);
        queryBuilder.withQuery(basicQuery);
        //2.2 设置 size为1，减少hits的数据
        queryBuilder.withPageable(PageRequest.of(0,1));
        //2.3 显示空的source
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //3.添加聚合条件
        String categoryAgg = "categoryAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(categoryAgg).field("categoryId"));
        String brandAgg = "brandAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(brandAgg).field("brandId"));
        //4.查询聚合结果
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);
        //5.解析聚合结果
        Aggregations aggs = result.getAggregations();
        //5.1 解析分类的聚合
        List<Long> idList = handleCategoryAgg(filterList, aggs.get(categoryAgg));
        //5.2 解析品牌的聚合
        handleBrandAgg(filterList,aggs.get(brandAgg));
        //5.3 处理规格参数
        if (idList !=null && idList.size()==1){
            handleSpecAgg(idList.get(0),basicQuery,filterList);
        }

        return filterList;
    }




    private void handleSpecAgg(Long cid, QueryBuilder basicQuery, Map<String, List<?>> filterList) {

        //1. 根据id分类查询这个分类下需要搜索的规格参数
        List<SpecParamDTO> params = itemClient.querySpecParams(null, cid, true);
        //2. 构建原生搜索构件器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //2.1.搜索条件
        queryBuilder.withQuery(basicQuery);
        //2.2 设置 size为1，减少hits的数据
        queryBuilder.withPageable(PageRequest.of(0,1));
        //2.3 显示空的source
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //3. 对查询出的规格参数做聚合
        for (SpecParamDTO param : params) {

            //取出parms的name，作为聚合名称，
            String name = param.getName();
            //添加聚合
            queryBuilder.addAggregation(AggregationBuilders.terms(name).field("specs."+name));
        }
        //4.查询数据
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);
        //5.解析集合结果放到filterList中
        Aggregations aggs = result.getAggregations();
        //解析每个参数的聚合结果
        for (SpecParamDTO param : params) {
            //取出parms的name，作为聚合名称
            Terms tarms = aggs.get(param.getName());
            //取出桶中的结果直接作为待选项
            List<String> options = tarms.getBuckets().stream()
                    .map(Terms.Bucket::getKeyAsString)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            //放到map中去
            filterList.put(param.getName(),options);
        }
    }





    private void handleBrandAgg(Map<String, List<?>> filterList, Terms terms) {
        //取出聚合中的桶，并处理成id的集合
        List<Long> idList = terms.getBuckets().stream()
                .map(bucket -> bucket.getKeyAsNumber().longValue())
                .collect(Collectors.toList());
        //根据id 的集合查询分类集合
        List<BrandDTO> options = itemClient.queryBrandByIds(idList);
        //放到map中去
        filterList.put("品牌",options);
    }




    private List<Long> handleCategoryAgg(Map<String, List<?>> filterList, Terms terms) {
        //取出聚合中的桶，并处理成id的集合
        List<Long> idList = terms.getBuckets().stream()
                .map(bucket -> bucket.getKeyAsNumber().longValue())
                .collect(Collectors.toList());
        //根据id 的集合查询分类集合
        List<CategoryDTO> options = itemClient.queryCategoryByIds(idList);
        //放到map中去
        filterList.put("分类",options);
        return idList;
    }




    public void saveItemIndex(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 构建成goods对象
        Goods goods = buildGoods(spu);
        // 保存数据到索引库
        goodsRepository.save(goods);
    }

    public void deleteById(Long spuId) {

        goodsRepository.deleteById(spuId);
    }
}
